package com.example.chat04.controller;

import com.example.chat04.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Controller;

import java.util.Objects;

@Controller
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Value("${redis.channel.msgToAll}")
    String msgToAll;
    @Value("${redis.set.onlineUsers}")
    String onlineUsers;

    @MessageMapping("/chat.public.sendMessage")
    public void sendMessage(@Payload ChatMessage chatMessage) {
        try {
            redisTemplate.convertAndSend(msgToAll,chatMessage);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 在这里往redis中广播用户上线的消息，并把用户名username写入redis的set中
     */
    @MessageMapping("/chat.public.addUser")
    public void addUser(ChatMessage chatMessage, StompHeaderAccessor stompHeaderAccessor){
        String sender = chatMessage.getSender();
        try {
            // Add username in web socket session
            Objects.requireNonNull(stompHeaderAccessor.getSessionAttributes()).put("username",sender);
            redisTemplate.opsForSet().add(onlineUsers,sender);
            redisTemplate.convertAndSend(msgToAll,chatMessage);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }


//    @MessageMapping("/chat.public.sendMessage")
//    @SendTo("/topic/chat.public")
//    public ChatMessage sendMessage(ChatMessage chatMessage){
//        return chatMessage;
//    }

//    @MessageMapping("/chat.public.addUser")
//    @SendTo("/topic/chat.public")
//    public ChatMessage addUser(ChatMessage chatMessage, StompHeaderAccessor stompHeaderAccessor){
//        // Add username in web socket session
//        Objects.requireNonNull(stompHeaderAccessor.getSessionAttributes()).put("username",chatMessage.getSender());
//        return chatMessage;
//    }

}
